#include "taskManager.h"
#include "Util/TimeTicker.h"
#include "Util/logger.h"

INSTANCE_IMP(taskManager);
 bool taskManager::pushMsg(std::function<void()> task)
 {
    _taskqueue.push_task(std::move(task));
    return true;
 }
void taskManager::startThread(const string &name) {
    _thread.reset(new thread([this, name]() {
        onThreadRun(name);
    }), [](thread *ptr) {
        ptr->join();
        delete ptr;
    });
}

void taskManager::stopThread(bool drop_task) {
    TimeTicker();
    if (!_thread) {
        return;
    }
    _thread = nullptr;
}

taskManager::~taskManager() {
    stopThread(true);
}

bool taskManager::isEnabled() const {
    return _thread.operator bool();
}

void taskManager::onThreadRun(const string &name) {
    setThreadName(name.data());
    function<void()> task;
    _exit = false;
    while (!_exit) {
        _taskqueue.get_task(task);
        try {
            TimeTicker2(50, TraceL);
            task();
            task = nullptr;
        } catch (ThreadExitException &ex) {
            break;
        } catch (std::exception &ex) {
            WarnL << ex.what();
            continue;
        } catch (...) {
            WarnL << "catch one unknown exception";
            throw;
        }
    }
    InfoL << name << " exited!";
}